<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Authentication\AuthenticationService;
use Application\Model\Role as Role;
use Application\Service\FileService as FileService;

class AgenceTable
{
    protected $table ='Agence';
    protected $tableName ='Agence';
    
    protected $tableGateway;
    protected $authService;
    protected $fileService;

    public function __construct(TableGateway $tableGateway, AuthenticationService $authService, FileService $FileService)
    {
    	$this->tableGateway = $tableGateway;
    	$this->authService = $authService;
        $this->fileService = $FileService;
    }
    
    public function fetchAll()
    {
    	$authService = $this->authService;
    	
    	$resultSet = $this->tableGateway->select(function(Select $select) use($authService) {
    		if ($authService->hasIdentity() && ! Role::isEqualRole($authService, Role::ROLE_ADMIN)) {
    			
    			$datas = $authService->getStorage()->read();
    			$select->join('Utilisateur', 'Utilisateur.agenceId = Agence.id', array());
    			$select->where->equalTo('Utilisateur.id', $datas['id']);
    		}
	        $select->order('libelle ASC');
	    });
    	
    	return $resultSet;
    }
    
    public function fetchAllArray()
    {
        $resultSet = $this->fetchAll();
        
        $entities = array();
        
        foreach ($resultSet as $row) {
        	$agence = new Agence();
        	$agence->exchangeArray( (array) $row);
        	$entities[] = $agence;
        }
        
        return $entities;
    }
    
    public function toArray ($resultSet)
    {
        $entities = array();
        
        foreach ($resultSet as $row) {
            $obj = new Agence();
            $obj->exchangeArray( (array) $row);
            $entities[] = $obj;
        }
        
        return $entities;
    }
    
    /* retourne tous les pays utilisés dans des séjours */
    public function fetchAllUsed()
    {
        $resultSet = $this->tableGateway->select(function(Select $select){
            $select->quantifier('DISTINCT');
            $select->join('Sejour', 'Sejour.agenceId = Agence.id', array(), 'inner');
            $select->order('libelle ASC');
        });
        
        return $this->toArray ($resultSet);
    }

    public function getAgence($id)
    {
        $id = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        
        $agence = new Agence();
        $agence->exchangeArray( (array) $row);
        
        return $agence;
    }
    
    public function saveAgence(Agence $agence)
    {
        $data = (array) $agence;
        
        $id = (int)$agence->id;
        
        if ($id == 0) {
            $this->tableGateway->insert( $data);
            
            $id = $this->tableGateway->lastInsertValue;
        } else {
            if ($this->getAgence($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
        
        return $id;
    }
    
    public function addAgence($libelle)
    {
        $data = array(
            'libelle' => $libelle,
        );
        $this->tableGateway->insert($data);
    }
    
    public function updateAgence(Agence $agence)
    {
        $data = (array) $agence;
        
        $this->tableGateway->update($data, array('id' => (int) $agence->id));
    }
    
    public function deleteAgence($id)
    {
        $agenceCourant = $this->getAgence($id);

        $this->fileService->setRootPath( $id , $type = "agence");
        
        $agenceLogoImage = $this->fileService->retourne_nom_image_min ( $agenceCourant->imageUrl );

        $this->fileService->supprimeImageFileSystem ( $agenceLogoImage );// suppression image agence miniature

        $this->tableGateway->delete(array('id' => $id));
    }
    
    public function getAgenceByLibelle( $libelle )
    {
        $rowset = $this->tableGateway->select(array('libelle' => ucfirst( $libelle ) ));
        $row = $rowset->current();
        
        return $row;
    }

    public function initFiltresAgence ( $values )
    {
        $sql = new Sql($this->tableGateway->getAdapter());
        $select = $sql->select();
        
        $select->from($this->tableGateway->table)
                ->where->in("Agence.id", $values);

        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();
        
        return $this->toArray ($resultSet);
    }
}